#include "vinfobar.h"
#include "vmainwindow.h"
#include <QEvent>
#include <QPushButton>
VInfoBar::VInfoBar(QWidget *parent)
	: QWidget(parent)
	, m_pCloseButton(new QPushButton(this))
	, m_pMaximizeButton(new QPushButton(this))
	, m_pMinimizeButton(new QPushButton(this))
{
	setAttribute(Qt::WA_StyledBackground, true);//默认Qwidget类 无法设置颜色
	setFixedHeight(63);
	setStyleSheet("VInfoBar{background-color:#929496;}");
	initWindowControlButtons();
	initConnect();
	installEventFilter(this);//安装事件过滤器
}

VInfoBar::~VInfoBar()
{}

void VInfoBar::initConnect()
{
	connect(m_pMaximizeButton, &QPushButton::released, this, &VInfoBar::onMaximizeButtonReleased);//最大化
	connect(m_pMinimizeButton, &QPushButton::released, this, &VInfoBar::onMinimizeButtonReleased);//最大化
	connect(m_pCloseButton, &QPushButton::released, this, &VInfoBar::onCloseButtonReleased);//关闭
}

void VInfoBar::initWindowControlButtons()
{
	QString MizeStyleSheet = R"(
        QPushButton{border:none;}
        QPushButton:hover{background-color: #E2E2E2; }
        QPushButton:pressed{background-color: #D1D1D1; }
        }
     )";

	m_pMinimizeButton->setText("—");
	m_pMaximizeButton->setText("□");
	m_pCloseButton->setText("X");

	m_pMinimizeButton->resize(35, 25);
	m_pMaximizeButton->resize(35, 25);
	m_pCloseButton->resize(35, 25);

	m_pMinimizeButton->setStyleSheet(MizeStyleSheet);
	m_pMaximizeButton->setStyleSheet(MizeStyleSheet);
	m_pCloseButton->setStyleSheet(R"(
        QPushButton{border:none;}
        QPushButton:hover{background-color: #FB7373; }
        QPushButton:pressed{background-color: #E14848; }
     )");
}

void VInfoBar::resizeEvent(QResizeEvent* event) //安放关闭按钮在右上角
{
	QWidget::resizeEvent(event);
	
	int w= m_pCloseButton->width();
	int x = width() - w;
	m_pCloseButton->move(x, 0);
	m_pMaximizeButton->move(x - w, 0);
	m_pMinimizeButton->move(x - 2 * w, 0);
}
void VInfoBar::onCloseButtonReleased()
{
	MainWindow()->close();
}
void VInfoBar::onMaximizeButtonReleased()
{
	if (MainWindow()->isMaximized()) MainWindow()->showNormal();
	else MainWindow()->showMaximized();
}

void VInfoBar::onMinimizeButtonReleased()
{
	MainWindow()->showMinimized();
}

bool VInfoBar::eventFilter(QObject* obj, QEvent* event)
{
	qDebug() << event->type();
	static QPoint s_pressPos;
	static QPoint s_widgetPos;
	switch (event->type())
	{
	case QEvent::MouseButtonPress:
		s_pressPos = QCursor::pos();//获取鼠标位置
		s_widgetPos = MainWindow()->pos();//获取控件的位置
		break;
	case QEvent::MouseButtonRelease:
		break;
	case QEvent::MouseMove:
			MainWindow()->move(s_widgetPos + QCursor::pos() - s_pressPos);
		break;
	}
	return false;
}